<?php

/**
 *		//图片处理类//
 *		//这是一份试验品，由大街编写（zhongmingzi@gmail.com）
 *		//本程序默认环境：Zend Optimizer Yes / 3.3.3
 *		//		Apache/2.0.63 (Win32) PHP/5.2.12
 *		//		MySQL 支持 Yes / client lib version 5.0.89
 *		//		GD library Yes / bundled (2.0.34 compatible)
 *		//		eAccelerator/Memcache/xcache Yes
 *		//		cURL support enabled
 *		//时间：2010 10 12 03:37:09//
 */
if(!defined('IN')) {
	exit('Access Denied');
}

define('IMG_ROOT', ROOT.'./data/');
define('TEMP_IMG_ROOT', IMG_ROOT.'./temp/');
$ftp_con = getglobal('setting/ftp');
define('ISFTP', $ftp_con['on']);
class image {

	var $thumbquality = 90;

	var $source = '';
	var $target = '';
	var $targetfixed = '';
	var $imginfo = array();
	var $imagecreatefromfunc = '';
	var $imagefunc = '';
	var $tmpfile = '';
	var $libmethod = 0;
	var $param = array('imagelib' => 0, 'imageimpath' => 0);//这里默认不使用IM库
	var $errorcode = 0;
	var $root = IMG_ROOT;
	var $tempdir = TEMP_IMG_ROOT;
	var $dirfix1 = '/s/';
	var $dirfix2 = '/ss/';
	
	var $isftp = ISFTP;
	
	function __construct($source) {
	
		$this->errorcode = 0;
		if(empty($source)) {
			$this->errorcode = -1;//源地址或源文件错误
			return;
		}
		$parse = parse_url($source);
		if(isset($parse['host'])) {//如果是远程的情况
			require_once libfile('function/favpic');
			$data = curl_img($source);
			if(!$data || $data < 0) {
				$data = dfsockopen($source);//print_r($data);exit;
			}
			dmkdir($this->tempdir);
			$this->tmpfile = $source = tempnam($this->tempdir, 'tmpimg_');
			file_put_contents($source, $data);
			if(!$data || $source === FALSE) {
				$this->errorcode = -2;//读取远程资源出错
				return;
			}
		} else $this->tmpfile = $source;
		
		clearstatcache();
		if(!is_readable($source)) {
			$this->errorcode = -3;//图像资源不可读
			return;
		}
		$imginfo = @getimagesize($source);
		if($imginfo === FALSE) {
			$this->errorcode = -4;//不可识别的图片资源
			return;
		}
		
		$this->source = $source;
		$this->imginfo['width'] = $imginfo[0];
		$this->imginfo['height'] = $imginfo[1];
		$this->imginfo['mime'] = $imginfo['mime'];
		$this->imginfo['size'] = @filesize($source);
		$this->libmethod = $this->param['imagelib'] && $this->param['imageimpath'];
		//不适用IM的时候
		if(!$this->libmethod) {
			switch($this->imginfo['mime']) {
				case 'image/jpeg':
					$this->imagecreatefromfunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : '';
					$this->imagefunc = function_exists('imagejpeg') ? 'imagejpeg' : '';
					break;
				case 'image/gif':
					$this->imagecreatefromfunc = function_exists('imagecreatefromgif') ? 'imagecreatefromgif' : '';
					$this->imagefunc = function_exists('imagegif') ? 'imagegif' : '';
					break;
				case 'image/png':
					$this->imagecreatefromfunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : '';
					$this->imagefunc = function_exists('imagepng') ? 'imagepng' : '';
					break;
			}
		} else {
			$this->imagecreatefromfunc = $this->imagefunc = TRUE;
		}
		if(!$this->libmethod && $this->imginfo['mime'] == 'image/gif') {
			if(!$this->imagecreatefromfunc) {
				$this->errorcode = -5;//gif图片处理函数不可用
				return;
			}
			if(!($fp = @fopen($source, 'rb'))) {
				$this->errorcode = -6;//gif图片读取失败
				return;
			}
			$content = fread($fp, $this->imginfo['size']);
			fclose($fp);
			$this->imginfo['animated'] = strpos($content, 'NETSCAPE2.0') === FALSE ? 0 : 1;
		}
	}
	
	function error() {
		return $this->errorcode;
	}

	function init($method, $target, $nosuffix = 0) {
		global $_G;

		if($method == 'thumb') {
			$target = empty($target) ?  $this->source.(!$nosuffix ? '.jpg' : '') : $this->root.'./'.$target;
		} elseif($method == 'watermask') {
			$target = empty($target) ?  $this->source : $this->root.'./'.$target;
		}
		$targetpath = dirname($target);
		dmkdir($targetpath);

		clearstatcache();
		if(!is_writable($targetpath)) {
			$this->errorcode = -7;//目标路径不可写入
			return;
		}
		
		//这里还得对后缀进行一个修正
		$target = $this->get_ext($target);
		$this->target = $target;
		return $this->imagecreatefromfunc ? 1 : 0;
	}
	
	function get_ext($target) {
		$img_ext = fileext($target);
		if($img_ext != 'jpg' && $img_ext != 'gif' && $img_ext != 'png' && $img_ext != 'jpeg') {
			switch($this->imginfo['mime']) {
				case 'image/jpeg':
					$new_ext = 'jpg';
					break;
				case 'image/gif':
					$new_ext = 'gif';
					break;
				case 'image/png':
					$new_ext = 'png';
					break;
				default:
					$new_ext = 'jpg';
			}
			$target = substr($target, 0, strlen($target) - strlen($img_ext)).$new_ext;
		}
		return $target;
	}


	function __destruct() {
		if($this->tmpfile) @unlink($this->tmpfile);
	}

	function sleep($return) {
		$this->imginfo['size'] = @filesize($this->target);
		if($this->isftp) @unlink($this->target);
		return $this->returncode($return);
	}

	function returncode($return) {
		if($return > 0 && file_exists($this->target) && $this->errorcode == 0) {
			return true;
		} else {
			return false;
		}
	}
	//这个函数留着给IM
	function exec($execstr) {
		exec($execstr, $output, $return);
		if(!empty($return) || !empty($output)) {
			return -11;//IM库执行失败
		}
		return true;
	}

	function loadsource() {
		$imagecreatefromfunc = &$this->imagecreatefromfunc;
		$im = @$imagecreatefromfunc($this->source);
		if(!$im) {
			if(!function_exists('imagecreatefromstring')) {
				$this->errorcode = -9;//imagecreatefromstring函数不能用
				return false;
			}
			$fp = @fopen($this->source, 'rb');
			$contents = @fread($fp, filesize($this->source));
			fclose($fp);
			$im = @imagecreatefromstring($contents);
			if($im == FALSE) {
				$this->errorcode = -10;//通过流读取图像资源失败
				return false;
			}
		}
		return $im;
	}
	//issub表示是否是小图片，默认是1，在s/，2级的话，在ss/，0的话直接按照target生成
	//如果width为0，则相当于单单的复制
	function thumb($target , $width = 0, $issquare = 1, $issub = 1, $isnat = 1, $nosuffix = 0) {
		//完成一些前期检测，创建文件夹等，把处理过的目标地址写入$this->target
		$return = $this->init('thumb', $target, $nosuffix);
		if($return == 0 || $this->errorcode < 0) {
			return $this->returncode($return);
		}

		//在这里做一个分支，如果是全尺寸复制，则直接使用文件复制以保留exif信息等。当尺寸大于1MB时则会压缩。
		$this->targetfixed = $this->get_ext($target);
		$max_size = 1048576;
		if(empty($width) && $this->imginfo['size'] <= $max_size) {
			if(@is_readable($this->source) && (@$fp_s = fopen($this->source, 'rb')) && (@$fp_t = fopen($this->target, 'wb'))) {
				while (!feof($fp_s)) {
					$s = @fread($fp_s, 1024 * 512);
					@fwrite($fp_t, $s);
				}
				fclose($fp_s); fclose($fp_t);
			}
		} else {
			//创建图像资源句柄到$sou_p
			if(!$sou_p = $this->loadsource()) {
				return $this->returncode(0);
			}
			$w = $this->imginfo['width'];
			$h = $this->imginfo['height'];
			
			if(empty($width)) {
				$is_w = true;
				$width = $w > 1280 && $this->imginfo['size']  > $max_size ? 1280 : ($h > 1280 && $this->imginfo['size']  > $max_size ? 550 : $w);
				$issquare = 0;
				$issub = 0;
			}
			
			if($w <= $width && $issquare == 0) {
				$is_w = true;
			}

			if($issquare == 1) {//正方形的时候，一般是必须生成的，不考虑动画。
				if($w > $h) {
					$tx = ($w - $h) / 2;
					$ty = 0;
					$tw = $th = $h;
					$lw = $lh = $width;
				} else {
					$tx = 0;
					$ty = ($h - $w) / 2;
					$tw = $th  = $w;
					$lw = $lh = $width;
				}
			} elseif($this->imginfo['animated'] == 0 && $issquare == 0) {//非正方形时不对动态转换,而且只对超过的进行转换
				if($is_w == true) {
					$tx = $ty = 0;
					$lw = $w;
					$lh = $h;
					$tw = $w;
					$th = $h;
				} elseif($isnat = 0 && $w < $h && $is_w != true) {
					$tx = $ty = 0;
					$th = $h;
					$lh = $width;
					$tw = $w;
					$lw = ($width * $w) / $h;
				} else {
					$tx = $ty = 0;
					$lw = $width;
					$lh = ($width * $h)/$w;
					$tw = $w;
					$th = $h;
				}
			} else {
				$this->errorcode = -8;//动画不能缩小
				return $this->returncode(0);
			}

			if($issub != 0) {
				$path = dirname($this->target);
				$fname = basename($this->target);
				$fixname = 'dirfix'.$issub;
				dmkdir($path.$this->$fixname);
			}

			$tar_file =$issub == 0 ? $this->target : $path.$this->$fixname.$fname.'.jpg';
			$this->target = $issub == 0 ? $this->target : $tar_file;
			$target =$issub == 0 ? $target :  dirname($target).$this->$fixname.basename($target).'.jpg';
			$tar_p = imagecreatetruecolor($lw, $lh);
			$imageout = $this->imagefunc;
			@imagecopyresampled($tar_p, $sou_p, 0, 0, $tx, $ty, $lw, $lh, $tw, $th);
			clearstatcache();
			if($this->imginfo['mime'] == 'image/jpeg') $imageout($tar_p, $tar_file, $this->thumbquality);
			else $imageout($tar_p, $tar_file);
		}
		//这里增加对FTP情况下的图片附件转移//这里使用$target表示相对地址//这里的删除文件要放到sleep后，因为析构函数只在类结束的时候删除
		if($this->isftp) ftpcmd('upload', $target);

		return $this->sleep(1);
	}
}

?>
